package JDBC;

import util.JDBCUtils;

/*登录方法使用新方法*/

import java.sql.*;
import java.util.Scanner;

public class jdbc_logen2 {
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    public static void main(String[] args) {
        //键盘录入,接受用户名和密码
        Scanner sc = new Scanner(System.in);
        String username = sc.next();
        String password = sc.next();
        boolean flag =  new jdbc_logen().login(username,password);
        if(flag)
        {
            System.out.println("成功");
        }
        else
        {
            System.out.println("失败");
        }
    }
    public boolean login(String username,String password)
    {
        if(username==null||password==null)
        {
            return false;
        }
        //连接数据库
        try {
            conn = DriverManager.getConnection("jdbc:mysql:///db","root","root");
            String sql = "select * from USER where username = ? and password = ?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            //改用PreparedStatement方法来获取对象
            pstmt.setString(1,username);
            pstmt.setString(2,password);
            //这里是为?赋值,sql的索引是从1开始的
            rs = pstmt.executeQuery();
            //因为换了pstmt了,所以可以不用传参
            //又因为stmt是pstmt的父类,所以释放的方法一样可以用
            return rs.next();
            //有下一行返回true
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(rs,pstmt,conn);
        }
        return false;
    }
}
